﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using JSON;

public class ListItem : MonoBehaviour {
	GameObject m_ChooseObj;
	GameObject ChooseObj{
		get{
			if (m_ChooseObj == null)
				m_ChooseObj = MyObj.GetGameObject ("Choose");
			return m_ChooseObj;
		}
	}
	MyOBJ c_MyObjs;
	int i_Value;
	int i_ID;
	JSONNode j_json;
	public delegate void UIListItemCallBack(ListItem listitem);
	public event UIListItemCallBack m_OnClick;
	public MyOBJ MyObj{
		get{	
			if(c_MyObjs  == null)
					return GetObj();
			return c_MyObjs;}
		set{c_MyObjs = value;}
	}
	MyOBJ GetObj(){
		if(c_MyObjs == null)
			c_MyObjs = GetComponent<MyOBJ>();
		return c_MyObjs;
	}
	public int Value{
		get{ return i_Value;}
		set{ i_Value = value;}
	}
	public int ID
	{
		get{ return i_ID;}
		set{ 
				if(i_ID != value)
				i_ID = value;	
			}
	}

	public JSONNode JSON{
		get{ 	return j_json;}
		set{
				j_json = value;
		}
	}
//	var cb_OnClick:Function;

	public static ListItem Init(GameObject obj,string listtype,int id,UIListItemCallBack cb){
		return Init(obj,listtype,id,0,cb);
	}
	public static ListItem Init(GameObject obj,string listtype,int id,int value,UIListItemCallBack cb){
		ListItem li;
		li = obj.GetComponent<ListItem>();
		if(li == null){
			li = obj.AddComponent<ListItem>();

		}
		li.i_ID = id;
		li.i_Value = value;
		li.m_OnClick = cb;

		Button button;
		button = obj.GetComponent<Button>();
		if(button){
			li.SetButton(button);
		}
		return li;
	}
	public void AddButtonCallBack(string name,EventDelegate cb){
		UIButton uibutton = MyObj.GetGameObject (name).GetComponent<UIButton> ();
		if (uibutton != null) {
			uibutton.gameObject.name = ID.ToString();
			uibutton.onClick.Clear();
			uibutton.onClick.Add(cb);
		}
	}
	public void UnChoose(){
		ChooseObj.SetActive (false);
	}
	public void Choose(){
		ChooseObj.SetActive (true);
	}
	void SetButton(Button button){
		button.onClick.RemoveAllListeners();
		button.onClick.AddListener(ONCLICK);
	}
	void ONCLICK(){
		if(m_OnClick != null)
			m_OnClick(this);
	}
	void OnClick(){
		if(m_OnClick != null)
			m_OnClick(this);
	}

}
